package org.csu.chatserver.handler;


import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.csu.chatserver.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

/*
*
*---------------------------这个类已经被废弃------------------------
*
*
*
*
*--------------------请看WebSocketHandlerDispatcher--------------------
*/
public class TcpServerHandler extends SimpleChannelInboundHandler<String> {


    private final UserService userService;

    public TcpServerHandler(UserService userService) {
        this.userService = userService;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) {
        System.out.println(msg);
        ctx.writeAndFlush("接收响应");

//        try {
//            JSONObject json = new JSONObject(msg);
//            String type = json.getString("type");
//            String username = json.getString("username");
//            String password = json.getString("password");
//
//            JSONObject response = new JSONObject();
//            if ("register".equalsIgnoreCase(type)) {
//                boolean success = userService.register(username, password);
//                response.put("status", success ? "SUCCESS" : "FAIL");
//                response.put("message", success ? "注册成功" : "用户名已存在");
//            } else if ("login".equalsIgnoreCase(type)) {
//                boolean valid = userService.login(username, password);
//                response.put("status", valid ? "SUCCESS" : "FAIL");
//                response.put("message", valid ? "登录成功" : "用户名或密码错误");
//            } else {
//                response.put("status", "ERROR");
//                response.put("message", "未知操作类型");
//            }
//            ctx.writeAndFlush(response.toString() + "\n");
//        } catch (JSONException e) {
//            JSONObject error = new JSONObject();
//            error.put("status", "ERROR");
//            error.put("message", "无效的请求格式");
//            ctx.writeAndFlush(error.toString() + "\n");
//        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
